<?php

namespace app\shop\controller\appsetting;

use app\shop\controller\Controller;
use app\shop\model\app\AppContent as AppContentModel;

/**
 * 内容管理
 */
class AppContent extends Controller
{
    /**
     * 获取数据
     */
    public function index()
    {
        $lists = AppContentModel::where("app_id", $this->store['app']['app_id'])->append(['position_label'])->order('position,sort desc')->select();
        $label = AppContentModel::POSITION_LABEL;
        return $this->renderSuccess('操作成功', [
            'lists' => $lists,
            'label' => $label,
        ]);
    }

    public function positionLabel()
    {
        return $this->renderSuccess('操作成功', [
            'label' => AppContentModel::POSITION_LABEL,
        ]);
    }

    /**
     * 保存数据
     */
    public function save()
    {
        $data = $this->postData();
        $id = $data['id'] ?? 0;
        if ($id > 0) {
            $content = AppContentModel::find($id);
            if (!$content || $content['app_id'] != $this->store['app']['app_id']) {
                return $this->renderError('非法操作');
            }
            $content->save($data);
        } else {
            unset($data['id']);
            $data['app_id'] = $this->store['app']['app_id'];
            AppContentModel::create($data);
        }
        return $this->renderSuccess('');
    }

    public function delete()
    {
        $id = input("id");
        $content = AppContentModel::find($id);
        if (!$content || $content['app_id'] != $this->store['app']['app_id']) {
            return $this->renderError('非法操作');
        }
        $content->delete();
        return $this->renderSuccess('');
    }
}
